import router, { asyncRouter, constantRoutes } from './router'
import store from './store'
// import { Message } from 'element-ui' //提示框
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({ showSpinner: false }) // 进度条

const whiteList = ['/login', '/404'] // 白名单

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      // next如果有路径不会触发导航后置首尾  需要手动关闭进度条
      NProgress.done()
    } else {
      if (!store.getters.userId) {
        await store.dispatch('user/getUserInfo')
        const filterRoutes = asyncRouter.filter((item) => {
          return store.state.user.userInfo.roles.menus.includes(item.name)
        })
        store.commit('user/setRoutes', [...constantRoutes, ...filterRoutes])
        // 4. 动态添加到路由系统中
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      }

      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {
// 关闭进度条
  NProgress.done()
})
